import 'dart:async';

import 'package:app/services/address.dart';
import 'package:app/services/dio_manager.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:get/get_utils/src/get_utils/get_utils.dart';
import 'package:dio/dio.dart';

import '../common/colors.dart';

class CountOtherButton extends StatefulWidget {
  var _username;
  var type;

  CountOtherButton(this._username, {this.type = 'pass'});

  @override
  State<CountOtherButton> createState() => _CountOtherButtonState();
}

class _CountOtherButtonState extends State<CountOtherButton> {
  late Timer timer;

  int countotherTime = 0;

  /// 倒计时
  ///
  void startCountOtherTimer() {
    countotherTime = 59;

    const oneSec = Duration(seconds: 1);

    timer = Timer.periodic(oneSec, (timer) {
      setState(() {
        if (countotherTime < 1) {
          timer.cancel();
        } else {
          countotherTime--;
        }
      });
    });
  }

  /// 发送验证码点击
  void sendCodeClick() {
    if (countotherTime == 0) {
      countotherTime = 59;
      startCountOtherTimer();
    }
  }

  ///发送验证码;
  requestDataSendCode(var phoneStr) async {
    print(widget.type);
    print(phoneStr.replaceAll(new RegExp(r"\s+\b|\b\s"), ""));

    var params = FormData.fromMap({
      'mobile': phoneStr.replaceAll(new RegExp(r"\s+\b|\b\s"), ""),
      'type': '${widget.type}',
    });

    var json = await DioManager()
        .kkRequest(Address.sendCode, bodyParams: params, isShowLoad: true);

    if (json['errmsg'] == 'ok') {
      sendCodeClick();
    }

    BotToast.showText(text: '${json['message']}');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 120,
      height: 40,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        border: Border.all(width: 1, color: AppColor.themeColor),
        borderRadius: const BorderRadius.all(Radius.circular(20)),
      ),
      child: GestureDetector(
        child: Text(
          countotherTime > 0 ? '重新发送($countotherTime)' : '获取验证码',
          style: TextStyle(
            color: AppColor.themeColor,
          ),
        ),
        onTap: () {
          if (!GetUtils.isPhoneNumber(widget._username.text)) {
            // Toast.toast(context,msg: '请输入正确的手机号码');
            BotToast.showText(text: '请输入正确的手机号码');
            return;
          }
          if (widget._username.text.isEmpty) {
            BotToast.showText(text: '请输入正确的手机号码');
            return;
          }

          requestDataSendCode(widget._username.text);
        },
      ),
    );
  }
}
